import { Bar } from "@ant-design/charts"
import { ProductRatingQuery, ProductRatingReport, TotalProductRatingCounts, TotalProductRatings } from "@mallfoundry/report"
import { Card, Col, Rate, Row, Statistic } from "antd"
import * as React from "react"
import { useEffect, useState } from "react"
import classes from "./product-ratings.module.scss"

const VALUE_FIELD_NAME = "评价数量"

interface ProductRatingsBarProps {
  storeId: string
}

function ProductRatingsBar(props: ProductRatingsBarProps) {
  const { storeId } = props
  const [totalProductRatingCounts, setTotalProductRatingCounts] = useState(new TotalProductRatingCounts())
  const asyncFetch = () => {
    ProductRatingReport
      .queryTotalProductRatingCounts(new ProductRatingQuery().toBuilder().storeId(storeId).build())
      .then(setTotalProductRatingCounts)
  }
  useEffect(asyncFetch, [storeId])

  const { fiveRatingCount, fourRatingCount, threeRatingCount, twoRatingCount, oneRatingCount } = totalProductRatingCounts

  const data = [
    {
      rating: "五星",
      [VALUE_FIELD_NAME]: fiveRatingCount,
    },
    {
      rating: "四星",
      [VALUE_FIELD_NAME]: fourRatingCount,
    },
    {
      rating: "三星",
      [VALUE_FIELD_NAME]: threeRatingCount,
    },
    {
      rating: "二星",
      [VALUE_FIELD_NAME]: twoRatingCount,
    },
    {
      rating: "一星",
      [VALUE_FIELD_NAME]: oneRatingCount,
    },
  ]
  const config = {
    height: 160,
    padding: [12, 0, 12, 32],
    barSize: 20,
    forceFit: true,
    data,
    xField: [VALUE_FIELD_NAME],
    yField: "rating",
    label: {
      visible: true,
    },
    xAxis: {
      visible: false,
    },
    tooltip: {
      showTitle: true,
    },
  }
  return <Bar {...config} />
}


interface ProductRatingsProps {
  storeId: string
}

export default function ProductRatings(props: ProductRatingsProps) {
  const { storeId } = props

  const [totalProductRatings, setTotalProductRatings] = useState(new TotalProductRatings())
  const asyncFetch = () => {
    ProductRatingReport
      .queryTotalProductRatings(new ProductRatingQuery().toBuilder().storeId(storeId).build())
      .then(setTotalProductRatings)
  }
  useEffect(asyncFetch, [storeId])

  const { averageRating } = totalProductRatings

  return (
    <Card title="商品评价" size="small" className={classes.ProductRatings}>
      <Row align="middle" gutter={[16, 0]}>
        <Col>
          <Statistic value={averageRating} className={classes.ProductRatingsStatistic}/>
        </Col>
        <Col>
          <Rate allowHalf value={averageRating} disabled/>
        </Col>
      </Row>
      <ProductRatingsBar storeId={storeId}/>
    </Card>
  )
}
